import UserImformation.Account;
import java.io.IOException;
import java.util.List;
import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String user_name = req.getParameter("user_name");
        String password1 = req.getParameter("password1");

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("myDateBase");
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        int exit = 0;

        String jpql = "select a from Account a where a.username = :username";
        Query query = em.createQuery(jpql);
        query.setParameter("username",user_name);
        List result = query.getResultList();

        if(result.size() != 0) {
            Account account = null;
            account = em.find(Account.class, user_name);
            if (account != null) {
                exit = 1;
            }
        }

        if(exit == 0) {
            Account account = null;
            account = em.find(Account.class, user_name);
            String sql = "SELECT MAX(a.user_number) FROM Account a";
            query = em.createQuery(sql, int.class);
            int num = (int) query.getSingleResult();
            int user_number = num + 1;
            account = new Account(user_number, user_name, null, null, null, null, null, null, "One_Piece.png", password1);
            em.persist(account);
            tx.commit();
        }

        em.close();
        String json = "{\"exit\":\"" + exit + "\"}";
        resp.setContentType("application/json, charset = utf-8");
        resp.getWriter().println(json);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doPost(req, resp);
    }
}
